<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .home {
      color: black;
      text-decoration: none;
      position: fixed;
      top: 20px;
      left: 20px;
      font-size: 20px;
    }

    h1 {
      text-align: center;
      margin-top: 20px;
    }

    ul {
      list-style: none;
    }

    .box li {
      padding: 20px;
      margin: 20px;
      border: 2px solid #ccc;
      cursor: pointer;
    }

    .box p {
      margin-bottom: 10px;
      font-size: 16px;
      pointer-events: none;
    }

    .box span {
      font-size: 12px;
      color: orangered;
      pointer-events: none;
    }
  </style>
</head>

<body>
  <a class="home" href="/client/index">返回首页</a>
  <h1>我的博客</h1>
  <ul class="box">

  </ul>
  <script type="module">
    import axios from "/client/axios.js"
    // 获取本地
    const id = JSON.parse(localStorage.getItem("user"))._id
    const box = document.querySelector(".box")
    // 获取博客
    let blogArr = []

    getData()

    // ul事件委托
    box.onclick = function (e) {
      if (e.target.nodeName != "LI") return
      console.log(e.target.dataset.id);
      let index = e.target.dataset.id
      const str = JSON.stringify(blogArr[index])
      sessionStorage.setItem("html", str)
      location.href = "./detail.html"
    }

    // 获取数据
    function getData() {
      axios.post("/blog/get", { id })
        .then(({ data: res }) => {
          console.log(res);
          blogArr = res.data.blog
          box.innerHTML = blogArr.reduce((pre, ele, index) => {
            const date = new Date(ele.time)
            return pre + `
            <li data-id=${index}>
              <p>${ele.title}</p>
              <span>发布时间: ${date.toLocaleString()}</span>
            </li>
            `
          }, "")
          if (blogArr.length == 0) {
            box.innerHTML = "<h2 style='margin:50px;text-align:center'>您还没有任何博客</h2>"
          }
        })
    }
  </script>
</body>

</html>